<?php

namespace app\api\controller;

use app\admin\model\Order as OrderModel;
use app\admin\model\recharge\Config;
use app\common\controller\Api;
use app\admin\model\recharge\Order;
use app\common\model\User;
use think\Log;
// 加载基础 adapay 基础类
// SDK 初始化文件加载
include_once  dirname(__FILE__). "/../../../extend/adapay/AdapaySdk/init.php";
// 在文件中设置 DEBUG 为 true 时， 则可以打印日志到指定的日志目录下 LOG_DIR
include_once  dirname(__FILE__). "/../../../extend/adapay/AdapaySdk/config.php";
/**
 * 充值接口
 */
class Recharge extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['list'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 充值配置
     */
    public function list()
    {
        $list = Config::order('weigh','desc')->select();
        $this->success('返回成功', $list);
    }

    /*
     * 创建充值订单
     * */
    public function recharge()
    {
        $params = $this->request->param();
        $id = $this->request->post('id',0);
        $recharge_info = Config::where('id',$id)->find();
        if (!$recharge_info){
            $this->error('充值信息有误');
        }
        $user = $this->auth->getUser();
        $has_recharge_order = Order::where(['user_id'=>$user['id'],'status'=>'20'])->find();
//        if (!$has_recharge_order && $recharge_info['money']<200){
//            $this->error('首次充值需大于200');
//        }
//        $params['method']=='mp' &&
        if (!$user['open_id']){
            $this->error('请先绑定微信');
        }
        $user_id = $this->auth->getUser()['id'];

        $recharge_order_no = build_order_no();
        $now = time();
        $rechargeOrderData = [
            'money'                => $recharge_info['money'],
            'pay_money'            => $recharge_info['pay_money'],
            'gift_money'           => $recharge_info['gift_money'],
//            'zuanshi'              => $recharge_info['zuanshi'],
            'user_id'              => $user_id,
            'order_time'           => date("Y-m-d H:i:s",$now),
            'order_no'             => $recharge_order_no,
            'status'               => 10
        ];

//        $rechargeOrderData['pay_money'] = 0.01;
        //开始组装下单数据
//        $pay_data = [
//            'amount'       => $rechargeOrderData['pay_money'],
//            'orderid'      => $recharge_order_no,
//            'type'         => 'wechat',
//            'title'        => "充值余额",
//            'notifyurl'    => request()->domain()."/addons/epay/api/notifyx/type/wechat/order_type/recharge",
//            'returnurl'    => request()->domain()."/h5/#/",
//            'method'       => 'mp',
//            'openid'       => $user['open_id'],
//            'auth_code'    => ''
//        ];
//        $pay_result = \addons\epay\library\Service::submitOrder($pay_data);
//        $pay_result = orderModel::wxpay($recharge_order_no, $rechargeOrderData['pay_money'], 'wechat', 'mp', '', $user['open_id'] , '','recharge');
//        if (!$pay_result){
//            Log::error('充值订单失败');
//            Log::error($pay_result);
//            $this->error('下单失败');
//        }
        //adapay微信公众号
        # 初始化支付类
        $payment = new \AdaPaySdk\Payment();
        $epay = get_addon_config('epay');
        # 支付设置
//        $total_fee = $rechargeOrderData['pay_money'];
        $total_fee=0.01;
        $request = \think\Request::instance();
        $payment_params = array(
            "app_id"=> 'app_55261a80-08ed-435c-bdd8-c11dfeff7a55',
            "order_no"=> $recharge_order_no,
            "pay_channel"=> "wx_pub",
            "time_expire"=> datetime($now+300,'YmdHis'),
            "pay_amt"=> $total_fee,
            "expend"=>[
                'open_id'=>$user['open_id'],
                'wx_app_id'=>$epay['wechat']['app_id'],
            ],
            "notify_url"  => $request->root(true) . '/api/adapay/asyncNotify/order_type/recharge',
//            "return_url"  => $request->root(true) . '/h5/#/pages/mine/orderList?type=1',
            "goods_title"=> "新视界",
            "goods_desc"=> "新视界影院",
            "description"=> "新视界影院充值"
        );
        Log::info('adapay_wx_pub充值参数:');
        Log::info($payment_params);
        # 发起支付
        $payment->create($payment_params);
        # 对支付结果进行处理
        if ($payment->isError()){
//                        $this->error($payment->result);
            $this->error($payment->result['error_msg']);
        } else {
            //成功处理
            Order::insert($rechargeOrderData);

            $this->success('发起成功',$payment->result);
        }

//        $pay_result = json_decode($pay_result,true);
//        $this->success('充值下单', $pay_result);
    }

}
